<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/12 0012
 * Time: 上午 10:12
 */

namespace Admin\Model;

use Think\Model;

class GoodsCategoryModel extends Model {

    /**
     * 查询方法
     * @param string $find
     * @return mixed
     */
    public function getList($find = '*') {
        return $this->field($find)->where(array('status' => 1))->select();
    }

    /**
     * 增加节点
     * @return type
     */
    public function addCategory() {
        //实例化model
        $mysql_db = new \Admin\Logic\DbmysqlLogic();
        //调用nestedsets
        $nestedsets = new \Admin\Service\NestedSets($mysql_db, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');
        //执行插入语句
        return $res = $nestedsets->insert($this->data['parent_id'], $this->data, 'bottom');
    }
    /**
     * 逻辑删除
     * @param type $id
     * @return type
     */
    public function deleteCategory($id) {
        //通过id查找到内容
        $caterow = $this->where(array('id' => $id))->getField('id,lft,rght');
        //删除子元素,因为子元素的范围是在大于等于lft小于等于rght的位置
        $find = array(
            'lft' => array('egt', $caterow[$id]['lft']),
            'rght' => array('elt', $caterow[$id]['rght']),
        );
        return $this->where($find)->setField('status', 0);
    }
    
    /**
     * 用于修改分类
     */
    public function  updateCategory(){
        $parent_id = $this->getFieldById($this->data['id'],'parent_id');
        if($parent_id != $this->data['parent_id']){
            //2重新计算节点
            //2.1实例化nestedsets所需要的数据库连接
             $mysql_db = new \Admin\Logic\DbmysqlLogic();
            //2.2实例化nestedsets并告知它表名和相关字段名分别是什么
            $nestedsets = new \Admin\Service\NestedSets($mysql_db, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');
            //2.3执行移动的方法
            if($nestedsets->moveUnder($this->data['id'], $this->data['parent_id'], 'bottom')===false){
                $this->error = '不能将当前分类移动到其后代分类';
                return false;
            }
        }
        return $this->save();
        }
        
    }
